package com.chushouya.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Strings;
import com.general.framework.core.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 腾讯地图工具类
 */
@Slf4j
public class LbsUtil {

    /**
     * 逆地址解析
     * <a href="https://lbs.qq.com/service/webService/webServiceGuide/webServiceGcoder">逆地址解析</a>
     */
    private static final String GEOCODER = "https://apis.map.qq.com/ws/geocoder/v1/";

    /**
     * ip定位
     * <a href="https://lbs.qq.com/service/webService/webServiceGuide/webServiceIp">ip定位</a>
     */
    private static final String LOCATION_IP = "https://apis.map.qq.com/ws/location/v1/ip";

    /**
     * 地点搜索
     * <a href="https://lbs.qq.com/service/webService/webServiceGuide/webServiceSearch">地点搜索</a>
     */
    private static final String PLACE_SEARCH = "https://lbs.qq.com/service/webService/webServiceGuide/webServiceSearch";

    /**
     * 地理逆解析
     *
     * @param key 秘钥
     * @param lat 纬度
     * @param lng 经度
     * @return 返回示例: {province=广东省, nation=中国, city=深圳市, street=深南大道, district=南山区, street_number=深南大道9072号}
     */
    public static Map<String, String> geocoder(String key, String lat, String lng) {
        //请求腾讯位置服务
        String response = HttpClientUtil.httpGet(GEOCODER + "?key=" + key + "&location=" + lat + "," + lng);
//        log.info("geocoder response: {}", response);
        //判断请求结果
        JSONObject json = JSON.parseObject(response);
        if (json.getIntValue("status") != 0) {
            throw Ex.business(json.getString("message"));
        }
        JSONObject formattedAddresses = json.getJSONObject("result").getJSONObject("formatted_addresses");
        String address = formattedAddresses.getString("recommend");
        JSONObject adInfo = json.getJSONObject("result").getJSONObject("ad_info");
        log.info("geocoder response: {}", json);
        String adCode = adInfo.getString("adcode");
        Map<String, String> geoMap = new HashMap<>();
        geoMap.put("address", address);
        geoMap.put("adCode", adCode);
        //返回地理信息
        return geoMap;
    }

    /**
     * 根据ip查询地理位置
     *
     * @param ip ip地址
     * @return 返回示例: {province=广东省, nation=中国, city=深圳市, adcode=440305, district=南山区}
     */
    public static Map<String, String> locationIp(String key, String ip) {
        if(Objects.equals("127.0.0.1",ip)){
            ip = "183.14.29.66";
        }
        //请求腾讯位置服务
        String response = HttpClientUtil.httpGet(LOCATION_IP + "?ip=" + ip + "&key=" + key);
        //判断请求结果
        JSONObject json = JSON.parseObject(response);
        if (json.getIntValue("status") != 0) {
            throw Ex.business(json.getString("message"));
        }
        //返回地理信息
        return json.getJSONObject("result").getJSONObject("ad_info").toJavaObject(new TypeReference<Map<String, String>>() {
        });
    }

    /**
     * 根据地址返回经纬度
     */
    public static Map<String, String> locationGeocoder(String key, String address) {
        String url = Strings.format("{}?key={}&address={}", PLACE_SEARCH, key, address);
        try {
            String response = HttpClientUtil.httpGet(url);
            JSONObject json = JSON.parseObject(response);
            if (json.getIntValue("status") != 0) {
                throw Ex.business(json.getString("message"));
            }
            return json.getJSONObject("result").toJavaObject(new TypeReference<Map<String, String>>() {});
        } catch (Exception e) {
            log.error("Error fetching location for address: {}", address, e);
            throw Ex.business("地址解析失败");
        }
    }

    public static void main(String[] args) {
        String key = "TDKBZ-UN7HD-H5J45-PNEI3-TOJWJ-F7FCE";
        //地理逆解析
        Map<String, String> map = geocoder(key, "22.54190801552538", "113.95599593136595");
        System.out.println(map); //{province=广东省, nation=中国, city=深圳市, street=深南大道, district=南山区, street_number=深南大道9072号}
        //ip定位
        Map<String, String> map2 = locationIp(key, "183.14.29.66");
        System.out.println(map2); //{province=广东省, nation=中国, city=深圳市, adcode=440305, district=南山区}
    }
}
